<template>
  <div>
    <!-- 注册弹框 -->
    <el-dialog
      :visible.sync="registerDialogFormVisible"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="clearRegister"
      title="注册账号"
    >
      <el-form
        :model="registerRuleForm"
        :rules="registerRules"
        ref="registerRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerRuleForm.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerRuleForm.phone"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="registerRuleForm.code" placeholder="请输入验证码">
            <template slot="append">
              <el-button
                type="primary"
                v-if="captchaToggle"
                @click.stop="countdown"
                >发送验证码</el-button
              >
              <el-button v-else disabled>{{ countnum }} S</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            :type="pwdInpType"
            v-model="registerRuleForm.password"
            placeholder="请输入密码"
          >
            <el-button
              v-if="pwdEyeToggle"
              slot="append"
              class="iconfont icon-yanjing-biyan"
              @click="handleShowPwd"
            ></el-button>
            <el-button
              v-else
              slot="append"
              class="iconfont icon-yanjing1"
              @click="handleHidePwd"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            :type="conPwdInpType"
            v-model="registerRuleForm.confirmPassword"
            placeholder="请确认密码"
          >
            <el-button
              v-if="conPwdEyeToggle"
              slot="append"
              class="iconfont icon-yanjing-biyan"
              @click="handleShowConPwd"
            ></el-button>
            <el-button
              v-else
              slot="append"
              class="iconfont icon-yanjing1"
              @click="handleHideConPwd"
            ></el-button>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="resetForm('registerRuleForm')">取 消</el-button>
        <el-button type="primary" @click="handleRegister">注 册</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { mapState, mapMutations } from "vuex";

export default {
  components: {},
  data() {
    var checkPassEqual = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerRuleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      pwdEyeToggle: true,
      conPwdEyeToggle: true,
      pwdInpType: "password", // 密码输入框类型
      conPwdInpType: "password", // 确认密码输入框类型
      registerRuleForm: {
        username: "",
        phone: "",
        password: "",
        confirmPassword: "",
        code: "",
      },
      registerRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, message: "长度在不小于3个字符", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: this.$reg.phone,
            message: "手机号格式有误！请重新输入",
            trigger: "change",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: this.$reg.pwd,
            message: "请输入6-16位数字加字母",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          {
            validator: checkPassEqual,
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            pattern: this.$reg.code,
            message: "请输入4位数字",
            trigger: "blur",
          },
        ],
      },
      countnum: 60, // 短信间隔时间
      captchaToggle: true,
    };
  },
  computed: {
    ...mapState(["registerDialogFormVisible"]),
  },
  created() {},
  mounted() {},
  methods: {
    ...mapMutations([
      "showLoginDialog",
      "hideLoginDialog",
      "showRegisterDialog",
      "hideRegisterDialog",
    ]),
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.hideRegisterDialog();
      this.hideLoginDialog();
    },
    // 清除注册表单数据
    clearRegister() {
      this.registerRuleForm = {
        username: "",
        phone: "",
        password: "",
        confirmPassword: "",
        code: "",
      };
    },
    // 点击注册按钮
    handleRegister() {
      this.$refs.registerRuleForm.validate(async (valid) => {
        if (valid) {
          var { data: verifycaptchaResult } = await axios.get(
            `${this.$server}/verifycaptcha`,
            {
              params: {
                phone: this.registerRuleForm.phone,
                captcha: this.registerRuleForm.code,
                type: 1,
              },
            }
          );
          console.log(verifycaptchaResult, "注册校验验证码结果");
          if (verifycaptchaResult.code == 200) {
            var { data: res } = await axios.post(`${this.$server}/register`, {
              username: this.registerRuleForm.username,
              phone: this.registerRuleForm.phone,
              password: this.registerRuleForm.password,
            });
            console.log(res);
            if (res.code == 200) {
              window.sessionStorage.setItem(
                "telphone",
                this.registerRuleForm.phone
              );
              window.sessionStorage.setItem(
                "username",
                this.registerRuleForm.username
              );
              window.sessionStorage.setItem("avatar", res.data.avatar);
              // window.sessionStorage.setItem("server_token", data.token);
              this.hideRegisterDialog();
              this.showLoginDialog();
            }
          } else {
            this.$message.error(verifycaptchaResult.msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 密码框内容显隐
    handleShowPwd() {
      this.pwdInpType = "text";
      this.pwdEyeToggle = false;
    },
    handleHidePwd() {
      this.pwdInpType = "password";
      this.pwdEyeToggle = true;
    },
    // 确认密码框内容显隐
    handleShowConPwd() {
      this.conPwdInpType = "text";
      this.conPwdEyeToggle = false;
    },
    handleHideConPwd() {
      this.conPwdInpType = "password";
      this.conPwdEyeToggle = true;
    },
    // 发送验证码
    async sendCaptcha() {
      var { data: res } = await axios.get(`${this.$server}/sendcaptcha`, {
        params: {
          phone: this.registerRuleForm.phone,
          type: 1,
        },
      });
      // console.log(res);
      if (res.code == 200) {
        this.$message.success(res.msg);
      } else {
        this.$message.error(res.msg);
      }
    },
    // 点击发送验证码按钮
    countdown() {
      if (
        this.registerRuleForm.phone &&
        this.$reg.phone.test(this.registerRuleForm.phone)
      ) {
        axios
          .post(`${this.$server}/haveRegister`, {
            phone: this.registerRuleForm.phone,
          })
          .then((response) => {
            if (response.data.code == 200) {
              this.$message.error(response.data.msg);
            } else {
              this.sendCaptcha();
              this.captchaToggle = false;
              var timer = setInterval(() => {
                if (this.countnum > 0) {
                  this.countnum--;
                  this.captchaToggle = false;
                } else {
                  clearInterval(timer);
                  timer = null;
                  this.countnum = 60;
                  this.captchaToggle = true;
                }
              }, 1000);
            }
          });
      } else {
        this.$message.error("请先输入正确的手机号");
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-dialog {
  height: max-content;
  padding: 30px;
  width: 40%;
}

::v-deep .el-dialog__header {
  text-align: center;
}
</style>
